<template>
    <div class="wiper">
        <Filter title="账号管理" :items="items" :model="filterModel" />
        <Table :columns="columns" :data="data" :pagination="filterModel"/>
        <Form ref="form" layout="horizontal" width="800" v-model:show="show" :rules="rules" :model="formModel" :items="formItems">

        </Form>
    </div>
</template>
<script>
    import Filter from "../../components/Filter";
    import Table from "../../components/Table";
    import Form from "../../components/Form";
    import {pager, save, remove, details} from "../../api/account";
    import {ColumnProps, RuleProps, FormProps,
        FilterItems, FormItems, FilterModelProps} from "./config";
    import {listAll} from "../../api/role/";
    import {listTree} from "../../api/organization";

    export default {
        name: 'account',
        data(){
            return{
                items: FilterItems,
                data: [],
                show: false,
                formModel: FormProps,
                rules: RuleProps,
                columns: ColumnProps,
                filterModel: {
                    ...FilterModelProps,
                    onChange: (page, pageSize)=>{
                        this.filterModel.current = page;
                        this.filterModel.pageSize = pageSize;
                        this.load();
                    }
                },
                formItems: FormItems,
                department: [],
                organization: [],
                post: [],
                role: []
            }
        },
        watch: {
          'formModel.organization': {
            handler: function (val, old) {
              if (old && old !== '' && val !== old) {
                this.formModel.dep = '';
                this.formModel.post = '';
              }
              this.formItems.forEach(item => {
                const department = item.filter(e => e.key === 'dep');
                department.length > 0 && (department[0].data = this._rename(this.department.filter(e => e.parentId === parseInt(val))) || []);
              })
            }
          },
          'formModel.dep': {
            handler: function (val, old) {
              console.log('val',val, 'old', old)
              console.log('post',this.formModel.post)
              if (old && old !== '' && val !== old) {
                this.formModel.post = '';
              }
              this.formItems.forEach(item => {
                const post = item.filter(e => e.key === 'post');
                post.length > 0 && (post[0].data = this._rename(this.post.filter(e => e.parentId === parseInt(val))) || []);
              })
            }
          },
        },
        components:{
            Filter,
            Table,
            Form
        },
        mounted(){
            this._listRoleAll();
            this._listTreeAll();
            this.load();
        },
        methods: {

            /**
             * 添加方法
             */
            add(){
                this.organization= [];
                this.department = [];
                this.post = [];
                this._listRoleAll();
                this._listTreeAll();
                this.formModel.id = "";
                this.rules = {password: [{ required: true, message: '登录密码不能为空' }], ...this.rules}
                this.$refs.form.resetField();
                this.show = true;
            },

            /**
             * 修改方法
             */
            modify(ids){
                this.show = true;
                delete this.rules.password
                details(ids.join(",")).then(res => {
                    this.formModel = res.data;
                })
            },

            /**
             * 删除方法
             */
            delete(ids){
                return new Promise((resolve, reject) => {
                    remove(ids.join(",")).then(res => {
                        this.load();
                        return resolve(res);
                    }).catch(e => {
                        return reject(e);
                    })
                })
            },

            /**
             * 提交
             */
            submit(){
                return new Promise((resolve, reject)=> {
                    this.formModel.roleIds = this.formModel.roleIds.join(",")
                    save(this.formModel).then(res => {
                        this.load();
                        this.formModel.roleIds = this.formModel.roleIds.split(",")
                        return resolve(res);
                    }).catch((e)=>{
                        return reject(e)
                    })
                })
            },


            /**
             * 加载数据
             */
            load(){
                pager(this.filterModel).then(res => {
                    res.data.rows
                    this.data = res.data.rows.map(item => {
                            return {
                                ...item, 
                                organizationName: this.organization.filter(i => i.id.toString() === item.organization)[0]?.name,
                                depName: this.department.filter(i => i.id.toString() === item.dep)[0]?.name, 
                                postName: this.post.filter(i => i.id.toString() === item.post)[0]?.name,
                            }
                        }
                    )
                    this.filterModel.total = res.data.total;
                })
            },

            /**
             * 重命名
             * @private
             */
            _rename(list, key = "id"){
                return list?.map(item => {
                    return {label: item.name, value: item[key].toString(),children: this._rename(item.children)}
                });
            },

            /**
             * 加载所有角色
             * @private
             */
            async _listRoleAll(){
                listAll().then(res => {
                    this.role = this._rename(res.data);
                    this._pushItems();
                })
            },

            /**
             * 组织机构树形
             * @private
             */
            async _listTreeAll(){
                listTree().then(res => {
                    console.log(res.data);
                    this._filterOrganization(res.data);
                })
            },

            /**
             * 过滤组织和部门
             * @param rows
             * @private
             */
            _filterOrganization(rows){
                rows.forEach(item => {
                    if(item.type === '0'){
                        this.organization.push(item);
                    }
                    if (item.type === '1'){
                        this.department.push(item);
                    }
                    if(item.type === '2'){
                        this.post.push(item);
                    }
                    this._filterOrganization(item.children || []);
                });
                this._pushItems();
            },

            /**
             * 把查询到的结果赋值到items中
             * @private
             */
            _pushItems(){
                this.formItems.forEach(item => {
                    const role = item.filter(e => e.key === 'roleIds');
                    const organization = item.filter(e => e.key === 'organization');
                    role.length > 0 && (role[0].data = this.role);
                    organization.length > 0 && (organization[0].data = this._rename(this.organization));
                })
            }
        }
    }
</script>
<style>

</style>
